package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.POrder;
import com.ruoyi.system.mapper.POrderMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.PMessageBo;
import com.ruoyi.system.domain.vo.PMessageVo;
import com.ruoyi.system.domain.PMessage;
import com.ruoyi.system.mapper.PMessageMapper;
import com.ruoyi.system.service.IPMessageService;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.Collection;


/**
 * 消息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-28
 */
@RequiredArgsConstructor
@Service
public class PMessageServiceImpl implements IPMessageService {

    private final PMessageMapper baseMapper;

    private final ISysDictTypeService iSysDictTypeService;

    private final POrderMapper pOrderMapper;

    /**
     * 查询消息
     */
    @Override
    public PMessageVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询消息列表
     */
    @Override
    public TableDataInfo<PMessageVo> queryPageList(PMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PMessage> lqw = buildQueryWrapper(bo);
        Page<PMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询消息列表
     */
    @Override
    public List<PMessageVo> queryList(PMessageBo bo) {
        LambdaQueryWrapper<PMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PMessage> buildQueryWrapper(PMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), PMessage::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), PMessage::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getSecondType()), PMessage::getSecondType, bo.getSecondType());
        lqw.eq(StringUtils.isNotBlank(bo.getMsg()), PMessage::getMsg, bo.getMsg());
        lqw.eq(bo.getCreateUserId() != null, PMessage::getCreateUserId, bo.getCreateUserId());
        lqw.eq(bo.getToUserId() != null, PMessage::getToUserId, bo.getToUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PMessage::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增消息
     */
    @Override
    public Boolean insertByBo(PMessageBo bo) {
        PMessage add = BeanUtil.toBean(bo, PMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改消息
     */
    @Override
    public Boolean updateByBo(PMessageBo bo) {
        PMessage update = BeanUtil.toBean(bo, PMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PMessage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除消息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Long messageCount() {
        Long userId = LoginHelper.getLoginUser().getUserId();
        return this.baseMapper.selectCount(new LambdaQueryWrapper<PMessage>().eq(PMessage::getToUserId, userId).eq(PMessage::getStatus, "0"));
    }

    @Override
    public Long  indexPersonCount() {
        List<SysDictData> list = this.iSysDictTypeService.selectDictDataByType("sys_index_person");
        Long num = new Long(list.get(0).getDictValue());
        long count = this.pOrderMapper.selectCount(new LambdaQueryWrapper<POrder>().eq(POrder::getDelFlag, "0"));
        return num + count;
    }

    @Override
    public TableDataInfo<PMessage> indexMessageIndex(List<String> secondType, PageQuery pageQuery) {
        Page<PMessage> pMessages = this.baseMapper.selectBySearch(pageQuery.build(), new LambdaQueryWrapper<PMessage>().in(PMessage::getSecondType, secondType)
                .eq(PMessage::getToUserId, LoginHelper.getUserId())
                .orderByDesc(PMessage::getCreateTime));
        if (secondType.contains("0")) {
            pMessages.getRecords().addAll(this.baseMapper.selectList(new LambdaQueryWrapper<PMessage>().eq(PMessage::getToUserId, null)));
        }
        return TableDataInfo.build(pMessages);
    }

    @Override
    public void sendMessage(PMessage pMessage) {
        pMessage.setSecondType("2");
        this.insertMessage(pMessage);
    }

    /**
     * 插入消息
     * @param pMessage
     */
    private void insertMessage(PMessage pMessage) {
        if (ObjectUtils.isEmpty(pMessage)) {
            throw new ServiceException("发送为空！");
        }
        if (ObjectUtils.isEmpty(pMessage.getToUserId())) {
            throw new ServiceException("未找到发送人");
        }
        PMessage pm = new PMessage();
        pm.setTitle(pMessage.getTitle())
            .setMsg(pMessage.getMsg())
            .setSecondType(pMessage.getSecondType())
            .setCreateUserId(LoginHelper.getUserId())
            .setToUserId(pMessage.getToUserId())
            .setStatus("0");
        if (this.baseMapper.insert(pm) != 1) {
            throw new ServiceException("发送失败!");
        }
    }
}
